﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HZU.ZP.Domain.IService;
using HZU.ZP.Domain.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HZU.ZP.Controllers
{
    public class CollectRecordController : Controller
    {
        private ICollectRecordService _collectRecordService;
        private IApplicantService _applicantService;
        public CollectRecordController(ICollectRecordService collectRecordService, IApplicantService applicantService)
        {
            _collectRecordService = collectRecordService;
            _applicantService = applicantService;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Applicant")]
        [HttpPost]
        public IActionResult AddCollect(string email, int positionId)
        {
            CollectRecord collectRecord = new CollectRecord();
            var applicant = _applicantService.GetApplicant(email);
            var collect = _collectRecordService.Get(applicant.Id.Value, positionId);
            if(collect!=null)
                return Json(AjaxResult.ReturnMessage(0, "已存在收藏记录"));
            collectRecord.ApplicantId = applicant.Id.Value;
            collectRecord.PositionId = positionId;
            _collectRecordService.Add(collectRecord);
            return Json(AjaxResult.ReturnMessage(1, "收藏成功"));
        }

        [Authorize(Roles = "Applicant")]
        [HttpPost]
        public IActionResult DeleteCollect(string email, int positionId)
        {
            var applicant = _applicantService.GetApplicant(email);          
            _collectRecordService.DeleteCollect(applicant.Id.Value, positionId);
            return Json(AjaxResult.ReturnMessage(1, "删除成功"));
        }

        [Authorize(Roles = "Applicant")]
        [HttpGet]
        public IActionResult GetAllCollect(string email)
        {
            if (User.Identity.Name != email)
            {
                return NotFound();
            }
            IList<Position> positionView = new List<Position>();         
            Applicant applicant = _applicantService.GetApplicant(email);
            //  CollectRecordView collectRecordView = new CollectRecordView();
            string sql = "select * from dbo.positions where id in (select positionId from dbo.collectRecords where applicantId =" + applicant.Id.Value + ")";
            positionView = _collectRecordService.GetAllCollect(sql);

            ViewData["Title"] = "收藏记录";
            return View(positionView);
        }
    }
}
